package com.woyao;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;

import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.CompanySummary;
import com.woyao.core.model.GetMyCompanyResponse;
import com.woyao.core.service.AccountService;
import com.woyao.core.util.ServiceFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

import retrofit2.Call;

public class FilterCompany extends AppCompatActivity {


    LinearLayoutManager allLayoutManager = null;
    private RecyclerView alllist = null;
    private CompanyAdapter allAdapter;


    ProgressDialog progressDialog;
    String content= "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_filter_company);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        //       ab.setHomeAsUpIndicator(R.drawable.icon_menu); // set a custom icon for the default home button
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout
//        ab.setDisplayShowTitleEnabled(false); // disable the default title element


        alllist = (RecyclerView) findViewById(R.id.id_how_list);
        allLayoutManager = new LinearLayoutManager(this);
        allLayoutManager.setOrientation(OrientationHelper.VERTICAL);
        alllist.setLayoutManager(allLayoutManager);
        alllist.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));


       this.setTitle("选择业务");

        Intent intent = getIntent();
        content = intent.getStringExtra("content");


        searchCompany( content);

    }



    private void searchCompany(final String content){
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("拼命加载中······");
        progressDialog.show();

        AsyncTask<Void,Void,GetMyCompanyResponse> task =
                new AsyncTask<Void, Void, GetMyCompanyResponse>() {
                    @Override
                    protected GetMyCompanyResponse doInBackground(Void... params) {
                        AccountService svc = ServiceFactory.get(AccountService.class);
                        Call<GetMyCompanyResponse> responseCall = svc.searchOrg(WoyaoooApplication.userId,content);
                        try {
                            GetMyCompanyResponse response = responseCall.execute().body();
                            return response;
                        } catch (IOException e) {
                            e.printStackTrace();
                            return null;
                        }
                    }
                    @Override
                    protected void onPostExecute(final GetMyCompanyResponse response) {
                        progressDialog.dismiss();
                        ArrayList<CompanySummary> hows = response.getCompanylist();
                        renderAll(hows);
                    }
                    @Override
                    protected void onCancelled() {
                        progressDialog.dismiss();
                    }
                };
        task.execute();
    }


    private void addOrg( final String org_title) {


        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("拼命加载中······");
        progressDialog.show();


        AsyncTask<Void, Void, BaseResponse> task = new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);

                Call<BaseResponse> responseCall = svc.addOrg(WoyaoooApplication.userId,  org_title);
                BaseResponse response = null;
                try {
                    response = responseCall.execute().body();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return response;
            }

            @Override
            protected void onPostExecute(final BaseResponse response) {
                if (response != null && response.isSuccess()) {
                    Intent intent = new Intent();
                    CompanySummary cs = new CompanySummary();
                    cs.setId(response.getMessage() );
                    cs.setTitle( org_title );
                    intent.putExtra("data", cs);
                    setResult(666, intent);
                    finish();
                }
                progressDialog.dismiss();
            }
            @Override
            protected void onCancelled() {
                progressDialog.dismiss();
            }
        };
        task.execute((Void) null);
    }


    private void renderAll( ArrayList<CompanySummary> items ){


        allAdapter = new CompanyAdapter(this,  items );
        allAdapter.setChangedHandler(new CompanyAdapter.Changed() {
            @Override
            public void view(CompanySummary thecompany) {
                getIt(thecompany );
            }


        });

        alllist.setAdapter(allAdapter);



    }

    private void getIt( final CompanySummary one ){


        if (one.getId().equals("0") ){
            addOrg(  one.getTitle() );

        }else {
            Intent intent = new Intent();
            intent.putExtra("data", one);
            setResult(666, intent);
            finish();
        }

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent = new Intent();
        CompanySummary one = new CompanySummary();
        one.setId("0");
        one.setTitle(content);
        intent.putExtra("data", one );
        setResult(666, intent);
        finish();

        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            CompanySummary one = new CompanySummary();
            one.setId("0");
            one.setTitle(content);
            intent.putExtra("data", one );
            setResult(666, intent);
            finish();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

}

